package com.liangjie.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ShowSession extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		HttpSession session = req.getSession(true);
		String head;
		Integer accessCount = (Integer)session.getAttribute("accessCount");
		
		if (accessCount == null) {
			accessCount = new Integer(0);
			head = "Hello, NewCommer!";
		} else {
			head = "Welcom Back!";
			accessCount = new Integer(accessCount.intValue() + 1);
		}
		
		session.setAttribute("accessCount", accessCount);
		
		pw.write("<h1>" + head + "</h1>");
		pw.write("<br/>");
		pw.write("ID:" + session.getId());
		pw.write("<br/>");
		pw.write("Create Time:" + new Date(session.getCreationTime()));
		pw.write("<br/>");
		pw.write("Last Access Time:" + new Date(session.getLastAccessedTime()));
		pw.write("<br/>");
		pw.write("Number of Access:" + accessCount);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
}
